package com.ad.pet.app.account.order;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ad.pet.DaggerMainActivityCompent;
import com.ad.pet.Logger;
import com.ad.pet.R;
import com.ad.pet.app.RxDisposable;
import com.ad.pet.app.account.adapter.OrderDetailGoodAdapter;
import com.ad.pet.app.account.order.fragment.OrderStatusContract;
import com.ad.pet.app.account.order.fragment.OrderStatusPresenter;
import com.ad.pet.common.data.http.BusCall;
import com.ad.pet.common.data.utils.ui.DialogUtil;
import com.ad.pet.common.data.utils.ui.ToastUtil;
import com.ad.pet.common.structure.events.RxBus;
import com.ad.pet.common.structure.mvp.BasePresenter;
import com.ad.pet.common.structure.ui.activity.AppToolbarActivity;
import com.ad.pet.models.remote.PayResult;
import com.ad.pet.models.remote.Wxpay;
import com.ad.pet.models.remote.account.order.BigOrder;
import com.ad.pet.models.remote.account.order.OrderType;
import com.ad.pet.ui.MaxRecyclerView;
import com.ad.pet.ui.PayChoseDialog;
import com.ad.pet.wxapi.PayContract;
import com.ad.pet.wxapi.PayPresenter;
import com.ad.pet.wxapi.WXPayUtils;
import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;

import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.android.schedulers.AndroidSchedulers;

/**
 * Created by liuyixiang on 2019/11/21.
 */

public class ServiceOrderDetailActivity extends AppToolbarActivity implements OrderStatusContract.View,PayContract.View{
    @BindView(R.id.iv_status)
    ImageView ivStatus;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.recyelr_good)
    MaxRecyclerView recyelrGood;
    @BindView(R.id.tv_good_fee)
    TextView tvGoodFee;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_quan)
    TextView tvQuan;
    @BindView(R.id.tv_count)
    TextView tvCount;
    @BindView(R.id.tv_order_number)
    TextView tvOrderNumber;
    @BindView(R.id.tv_order_time)
    TextView tvOrderTime;
    @BindView(R.id.tv_cancel)
    TextView tvCancel;
    @BindView(R.id.tv_pay)
    TextView tvPay;
    @BindView(R.id.linear_pay)
    LinearLayout linearPay;
    @BindView(R.id.tv_shouhuo)
    TextView tvShouhuo;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    private String orderId;
    @Inject
    PayPresenter mPayPresenter;
    static final int SDK_PAY_FLAG = 1;
    private int payType;
    private Handler deliver = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG:
//                    String resault = msg.obj.toString();
//                    LogUtils.e("pay_resault",resault);
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    String notifyUrl = payResult.getNotifyUrl();
                    // 判断resultStatus 为9000则代表支付成功
                    Logger.e("result_alipay:" + resultInfo + "|" + resultStatus + "|" + notifyUrl);
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        mStatusPresenter.getPacketInfo(orderId);
                        ToastUtil.getToastUtil().showShort(getString(R.string.pay_success));

                        RxBus.getDefault().post("confim_success");
//                        finish();
//                        RxBus.getDefault().post(new Events.PayStatusCallback(notifyUrl, "alipay", resultInfo));
                    } else {//支付失败
                        ToastUtil.getToastUtil().showShort(getString(R.string.pay_failed));

                    }
                    break;
            }
        }
    };
    @Inject
    RxDisposable mRxDisposable;
    @Inject
    OrderStatusPresenter mStatusPresenter;
    private OrderDetailGoodAdapter orderDetailGoodAdapter;
    PayChoseDialog payChoseDialog ;
    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        mStatusLayoutManager.showContent();
        mToolbar.setTitle("订单详情");
    }

    @Override
    protected int contentLayout() {
        return R.layout.activity_service_order_detail
                ;
    }

    @Override
    protected void clickRetry(View v) {

    }

    @Override
    protected void initViews() {
        mStatusPresenter.onCreate(this);
        mPayPresenter.onCreate(this);
        orderId = getIntent().getStringExtra("orderid");
        mStatusPresenter.getPacketInfo(orderId);

        recyelrGood.setLayoutManager(new LinearLayoutManager(this));
        orderDetailGoodAdapter = new OrderDetailGoodAdapter(null);
        recyelrGood.setAdapter(orderDetailGoodAdapter);
        payChoseDialog = new PayChoseDialog(mActivity,R.style.custom_dialog_style,false);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initEvents() {

        mRxDisposable.add(RxBus.getDefault().toObservable(String.class)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new BusCall<String>() {
                    @Override
                    public void call(String webTitle) {
                        if ("confim_success".equals(webTitle)) {
                            mStatusPresenter.getPacketInfo(orderId);
                        }
                    }
                }));
//        mRxDisposable.add(RxBus.getDefault().toObservable(Events.PayStatusCallback.class)
//                .observeOn(AndroidSchedulers.mainThread()).subscribe(new BusCall<Events.PayStatusCallback>() {
//                    @Override
//                    public void call(Events.PayStatusCallback webTitle) {
//                        if ("weixin_app".equals(webTitle.paytype)) {
//                            mStatusPresenter.getPacketInfo(orderId);
//                        }
//                    }
//                }));
        payChoseDialog.setOnGetPayWay(new PayChoseDialog.OnGetPayWay() {


            @Override
            public void getPayWay(int way) {
                payType = way;
                mPayPresenter.upPayresult(orderId,payType!=1?"2":"1");
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtil.createDialog(mActivity, "", "是否取消订单?", true, "取消", null, "确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mStatusPresenter.cancelOrder(orderId);
                    }
                }).show();
            }
        });
        tvPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//

                mPayPresenter.upPayresult(orderId,"");
            }
        });
    }

    @Override
    public void initInject() {
        DaggerMainActivityCompent.builder().applicationComponent(getApplicationComponent())

                .activityModule(getActivityModule()).build().inject(this);
    }

    @Override
    protected BasePresenter getPresenter() {
        return null;
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void error(String msg) {

    }

    @Override
    public void error(int code, String msg) {

    }

    @Override
    public void getPendingSuccess(List<BigOrder> bigOrder) {

    }

    @Override
    public void getPacketInfoSuccess(BigOrder bigOrder) {

        switch (bigOrder.getOrder_status()) {
            case "0":
                tvStatus.setText("待付款");
                tvTime.setText("请在" + "" + "完成付款");
                tvTime.setVisibility(View.VISIBLE);
                break;
            case "4":
                tvStatus.setText("已完成");
                tvTime.setVisibility(View.GONE);
                break;
            case "5":
                tvStatus.setText("已关闭");
                tvTime.setVisibility(View.GONE);
                break;
        }

        if ("0".equals(bigOrder.getOrder_status())) {
            linearPay.setVisibility(View.VISIBLE);
        } else {
            linearPay.setVisibility(View.GONE);
        }

        orderDetailGoodAdapter.setNewData(bigOrder.getOrder_offservice_list());
        tvPrice.setText("￥" + bigOrder.getGoods_money());
        tvQuan.setText("-￥" + bigOrder.getCoupon_money());
        tvCount.setText("￥" + bigOrder.getOrder_money());
        tvOrderNumber.setText(bigOrder.getOrder_no());
        tvShouhuo.setText(bigOrder.getShop_name());
        tvPhone.setText(bigOrder.getLive_store_address());

    }

    @Override
    public void getOrderStatusSuccess(List<BigOrder> orderStatuses) {

    }

    @Override
    public void cancelOrderSuccess() {
        RxBus.getDefault().post("confim_success");

        ToastUtil.getToastUtil().showShort("取消订单成功");
    }

    @Override
    public void confirmOrderSuccess() {

    }

    @Override
    public void getGoodOrderDetailSuccess(BigOrder bigOrder) {

    }

    @Override
    public void myAppointListSuccess(List<OrderType> list) {

    }

    @Override
    public void cancelAppointListSuccess() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void upPayresultSuccess(PayResult payResult) {
        payType =  Integer.valueOf(payResult.getPayment_type());
        if (payType==1) {

            WXPayUtils wxPayUtils = new WXPayUtils(mActivity);
            if (wxPayUtils.isWxAppInstalledAndSupported()) {


                Wxpay wxpay = new Wxpay(payResult.getAppid(), payResult.getPartnerid(), payResult.getPrepay_id(), payResult.getNonce_str(), payResult.getTimestamp(), payResult.getPackageq(), payResult.getSign(), "notify_url");
                wxPayUtils.doPay(new Gson().toJson(wxpay));
                Logger.d("jsonString--->" + new Gson().toJson(wxpay));
            }
        } else  {
            final String orderInfo = payResult.getAli_pay_str();   // 订单信息

            Runnable payRunnable = new Runnable() {

                @Override
                public void run() {
                    PayTask alipay = new PayTask(mActivity);
                    Map<String, String> result = alipay.payV2(orderInfo, false);
//                    result.put("notify_url", payUrl.getNotify_url());
                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    deliver.sendMessage(msg);
                }
            };
            // 必须异步调用
            Thread payThread = new Thread(payRunnable);
            payThread.start();
        }
        payChoseDialog.dismiss();
    }
}
